﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace BGYXControlLibrary.Common
{
    public static class BGYX_VisualTreeHelper
    {
        public static T GetParent<T>(DependencyObject ui) where T : DependencyObject
        {
            T obj = VisualTreeHelper.GetParent(ui) as T;
            if (obj == null) return null;
            if (obj is T)
            {
                return (T)obj;
            }
            return GetParent<T>(obj);
        }

        public static childItem FindVisualChild<childItem>(DependencyObject obj, string name) where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem && (name == null || name == (child as FrameworkElement)?.Name))
                    return (childItem)child;

                childItem childOfChild = FindVisualChild<childItem>(child, name);
                if (childOfChild != null)
                    return childOfChild;
            }
            return null;
        }
    }
}
